// src/pages/PermissionList/index.tsx
import React, {useState, useRef} from 'react';
import {
    PageContainer,
    ProColumns,
    ProTable,
} from '@ant-design/pro-components';
import {Button, Space, message, Modal, Tag, Dropdown} from 'antd';
import {PlusOutlined, DownOutlined} from '@ant-design/icons';
import {
    getPermissionList,
    deletePermission,
} from '@/services/permission';
import PermissionModal from './components/PermissionModal';
import SelectRoleModal from "@/pages/UserList/components/SelectRoleModal";
import { handleProTableRequest, callApi } from '@/utils/request';
import AuthorizedButton from '@/components/AuthorizedButton';

// 定义权限数据类型
type PermissionItem = {
    id: number;
    name: string;
    type: number;
    typeDesc: string; // 后端返回的类型文本
    code: string;
    url?: string;
    component?: string;
    permsType?: number;
    sortNo?: number;
    status?: number;
    description?: string;
    icon?: string; // 添加 icon 字段
};

// 定义查询参数类型
type PermissionQueryParams = {
    parentName?: string;
    code?: string;
    menuType?: string; // 筛选时可能传字符串
    sortField?: string;
    sortOrder?: string;
    pageNum?: number;
    pageSize?: number;
};

const PermissionList: React.FC = () => {
    const actionRef = useRef<any>(null);

    const [permissionModalVisible, setPermissionModalVisible] = useState<boolean>(false);
    const [currentPermission, setCurrentPermission] = useState<PermissionItem | undefined>(undefined);
    const [currentPermissionId, setCurrentPermissionId] = useState<number>(0);
    const [addParentPermissionId, setAddParentPermissionId] = useState<number>(0);
    const [isEdit, setIsEdit] = useState<boolean>(false);
    const [disableSubmit, setDisableSubmit] = useState<boolean>(false);

    const [roleModalVisible, setRoleModalVisible] = useState<boolean>(false);

    // 列定义
    const columns: ProColumns<PermissionItem>[] = [
        {
            title: '菜单名称',
            dataIndex: 'name',
            align: 'center',
            formItemProps: {
                // 查询表单项配置
            },
            fixed: "left"
        },
        {
            title: '菜单类型',
            dataIndex: 'typeDesc', // 显示字典文本
            align: 'center',
            width: 100,
            valueType: 'select',
            valueEnum: {
                '0': {text: '目录'},
                '1': {text: '菜单'},
                '2': {text: '按钮/权限'},
            },
            fixed: "left",
            search: false, // 不在查询表单中显示
            render: (_, record) => (
                <Tag color={record.type === 2 ? 'warning' : record.type === 1 ? 'success' : 'processing'}>
                    {record.typeDesc}
                </Tag>
            ),
        },
        {
            title: '权限编码',
            dataIndex: 'code',
            align: 'center',
            search: false, // 不在查询表单中显示
            width: 240,
            ellipsis: true, // 添加省略号配置
            fixed: "left",
        },
        {
            //TODO 初期靠手动填写
            title: 'icon',
            dataIndex: 'icon',
            align: 'center',
            search: false, // 不在查询表单中显示
            width: 150,
            ellipsis: true, // 添加省略号配置
        },
        {
            title: '组件',
            dataIndex: 'component',
            align: 'center',
            search: false, // 不在查询表单中显示
            width: 180,
            ellipsis: true, // 添加省略号配置
        },
        {
            title: '路径',
            dataIndex: 'url',
            align: 'center',
            search: false, // 不在查询表单中显示
            width: 180,
            ellipsis: true, // 添加省略号配置
        },
        {
            title: '排序',
            dataIndex: 'sortNo',
            align: 'center',
            search: false, // 不在查询表单中显示
        },
        {
            title: '操作',
            dataIndex: 'option',
            align: 'center',
            valueType: 'option',
            width: 150,
            fixed: 'right', // 固定到右侧
            render: (_, record) => (
                <Space size={10}>
                    <AuthorizedButton
                        type="link"
                        size="small"
                        onClick={() => handleEdit(record)}
                        code="permission_list_edit_btn" // 替换为实际权限码
                    >
                        编辑
                    </AuthorizedButton>
                    <Dropdown
                        menu={{
                            items: [
                                {
                                    key: 'detail',
                                    label: '详情',
                                    onClick: () => handleDetail(record),
                                },
                                {
                                    key: 'addChild',
                                    label: '添加子菜单',
                                    onClick: () => handleAddChild(record),
                                },
                                {
                                    key: 'delete',
                                    label: '删除',
                                    onClick: () => handleDelete(record),
                                },
                                {
                                    key: 'viewRole',
                                    label: '查看角色',
                                    onClick: () => handleShowRole(record),
                                },
                            ],
                        }}
                        trigger={['click']}
                    >
                        <AuthorizedButton
                            type="link"
                            size="small"
                            code="permission_list_more_btn" // 替换为实际权限码
                        >
                            更多 <DownOutlined/>
                        </AuthorizedButton>
                    </Dropdown>
                </Space>
            ),
        },
    ];

    // --- 操作方法 ---

    const handleAdd = () => {
        setIsEdit(false);
        setDisableSubmit(false);
        setCurrentPermission(undefined);
        setCurrentPermissionId(0);
        setPermissionModalVisible(true);
    };

    const handleAddChild = (record: PermissionItem) => {
        setIsEdit(false);
        setDisableSubmit(false);
        setCurrentPermission(undefined);
        setCurrentPermissionId(0);
        setAddParentPermissionId(record.id!);
        setPermissionModalVisible(true);
    };

    const handleEdit = (record: PermissionItem) => {
        setIsEdit(true);
        setDisableSubmit(false);
        setCurrentPermission(record);
        setCurrentPermissionId(record.id);
        setPermissionModalVisible(true);
    };

    const handleDetail = (record: PermissionItem) => {
        setIsEdit(true);
        setDisableSubmit(true);
        setCurrentPermission(record);
        setCurrentPermissionId(record.id);
        setPermissionModalVisible(true);
        setRoleModalVisible(false)
    };

    const handleShowRole = (record: PermissionItem) => {
        setIsEdit(false);
        setDisableSubmit(false);
        setCurrentPermission(record);
        setCurrentPermissionId(record.id);
        setPermissionModalVisible(false);
        setRoleModalVisible(true)
    };

    const handleDelete = (record: PermissionItem) => {
        Modal.confirm({
            title: '确认删除',
            content: `您确定要删除权限 "${record.name}" 吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                const result = await callApi(
                    () => deletePermission({id: record.id}),
                    { successMsg: '删除成功', errorMsg: '删除失败' }
                );

                if (result) {
                    // --- 修正：使用 null 检查，并等待 Promise ---
                    if (actionRef.current && actionRef.current.reload) {
                        await actionRef.current.reload();
                    }
                }
            },
        });
    };

    // --- 修正：将 handleModalOk 定义为 async 函数 ---
    const handleModalOk = async (formData: any) => {
        // 处理 PermissionModal 的确定事件
        console.log('PermissionModal OK:', formData);
        setPermissionModalVisible(false);
        // --- 修正：使用 null 检查，并等待 Promise ---
        if (actionRef.current && actionRef.current.reload) {
            await actionRef.current.reload(); // 重新加载表格
        }
    };

    const handleModalCancel = () => {
        setPermissionModalVisible(false);
    };

    return (
        <PageContainer>
            <ProTable<PermissionItem, PermissionQueryParams>
                headerTitle="权限管理"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 'auto',
                }}
                toolBarRender={() => [
                    <AuthorizedButton
                        key="add"
                        type="primary"
                        onClick={handleAdd}
                        code="permission_list_add_btn" // 替换为实际权限码
                    >
                        <PlusOutlined/>
                        新建
                    </AuthorizedButton>,
                ]}
                request={async (params, sorter, filter) => {
                    // 构造查询参数
                    const queryParams: PermissionQueryParams = {
                        pageNum: params.current,
                        pageSize: params.pageSize,
                        parentName: params.parentName,
                        code: params.code,
                    };
                    // 处理排序
                    if (Object.keys(sorter).length > 0) {
                        const sortField = Object.keys(sorter)[0];
                        const sortOrder = sorter[sortField]; // 'ascend' or 'descend'
                        queryParams.sortField = sortField;
                        queryParams.sortOrder = sortOrder === 'ascend' ? 'asc' : 'desc';
                    }
                    // 处理过滤 (filters)
                    // 根据实际情况处理 filter 参数

                    return handleProTableRequest<PermissionItem>(
                        () => getPermissionList(queryParams),
                        { errorMsg: '获取权限列表失败' }
                    );
                }}
                columns={columns}
                pagination={{
                    defaultPageSize: 10,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    pageSizeOptions: ['10', '20', '30'],
                }}
            />

            {/* Permission Modal */}
            <PermissionModal
                visible={permissionModalVisible}
                isEdit={isEdit}
                disableSubmit={disableSubmit}
                currentPermission={currentPermission}
                addParentPermissionId={addParentPermissionId}
                currentPermissionId={currentPermissionId}
                onOk={handleModalOk}
                onCancel={handleModalCancel}
            />

            {/* 角色列表模态框 */}
            {currentPermission && (
                <SelectRoleModal
                    visible={roleModalVisible}
                    queryType={2}
                    canOperate={false}
                    curPermissionId={currentPermission.id}
                    curPermissionName={currentPermission?.name}
                    onOk={() => {
                        setRoleModalVisible(false);
                    }}
                    onCancel={() => {
                        setRoleModalVisible(false);
                    }}
                />
            )}
        </PageContainer>
    );
};

export default PermissionList;